// Copyright 2016 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

// i2c-list lists all I²C buses.
package main

import (
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"openzbox.com/driver/conn/uart"
	"openzbox.com/driver/conn/uart/uartreg"
	"os"

	"openzbox.com/driver/conn/pin"
	"openzbox.com/driver/conn/pin/pinreg"
	"openzbox.com/driver/host"
)

func printPin(fn string, p pin.Pin) {
	name, pos := pinreg.Position(p)
	if name != "" {
		fmt.Printf("  %-3s: %-10s found on header %s, #%d\n", fn, p, name, pos)
	} else {
		fmt.Printf("  %-3s: %-10s\n", fn, p)
	}
}

func mainImpl() error {
	verbose := flag.Bool("v", false, "verbose mode")
	flag.Parse()
	if !*verbose {
		log.SetOutput(ioutil.Discard)
	}
	log.SetFlags(log.Lmicroseconds)
	if flag.NArg() != 0 {
		return errors.New("unexpected argument, try -help")
	}

	state, err := host.Init()
	if err != nil {
		log.Fatalf("failed to initialize periph: %v", err)
	}

	// Prints the loaded driver.
	fmt.Printf("Using drivers:\n")
	for _, driver := range state.Loaded {
		fmt.Printf("- %s\n", driver)
	}

	// Prints the driver that were skipped as irrelevant on the platform.
	fmt.Printf("Drivers skipped:\n")
	for _, failure := range state.Skipped {
		fmt.Printf("- %s: %s\n", failure.D, failure.Err)
	}

	// Having drivers failing to load may not require process termination. It
	// is possible to continue to run in partial failure mode.
	fmt.Printf("Drivers failed to load:\n")
	for _, failure := range state.Failed {
		fmt.Printf("- %s: %v\n", failure.D, failure.Err)
	}

	//nuc98x.InitWDT();
	/*

		for _, ref := range i2creg.All() {
			fmt.Printf("%s", ref.Name)
			if ref.Number != -1 {
				fmt.Printf(" #%d", ref.Number)
			}
			fmt.Print(":\n")
			if len(ref.Aliases) != 0 {
				fmt.Printf("  Aliases:\n")
				for _, a := range ref.Aliases {
					fmt.Printf("    %s\n", a)
				}
			}
			bus, err := ref.Open()
			if err != nil {
				fmt.Printf("  Failed to open: %v\n", err)
				continue
			}
			if p, ok := bus.(i2c.Pins); ok {
				printPin("SCL", p.SCL())
				printPin("SDA", p.SDA())
			}
			if err := bus.Close(); err != nil {
				return err
			}
		}*/
	return nil
}

func main() {
	if err := mainImpl(); err != nil {
		fmt.Fprintf(os.Stderr, "i2c-list: %s.\n", err)

		p, err := uartreg.Open("/dev/ttyS6")
		if err != nil {
			log.Fatal(err)
		}
		defer p.Close()

		// Prints out the gpio pin used.
		if p, ok := p.(uart.Pins); ok {
			fmt.Printf("  RX : %s", p.RX())
			fmt.Printf("  TX : %s", p.TX())
			fmt.Printf("  RTS: %s", p.RTS())
			fmt.Printf("  CTS: %s", p.CTS())
		}

		os.Exit(1)
	}
}
